22.02.16 - List Comprehensions
Set Comprehensions
Comprehension notation can be used to construct new sets from old sets
In haskell can be done with list comprehension
[x^2 | x <- [1..5]]
- The expression
x <- [1..5]
is a generator, states how to generate values for x. Can be used multiple times separated by commas. - Changing the order of the generators changes the order of the elements in the final list.
- Multiple generators are like nested loops, with later generators being more deeply nested loops
Dependant generators
Later generators can depend on the variables that are introduced by earlier generators Using a dependent generator we can define the library function that concatenates a lists of lists
Guards
Use guards to restrict the values produced by earlier generators
[x | x <- [1..10], even x]
Using a guard we can define a function that maps a positive integer to its list of factors
The zip function
zip :: [a] -> [b] -> [(a,b)]
- Maps two lists to a lists of pairs of their corresponding elements.
- Define a function that returns the list of app pairs of adjacent elements from a list
- Using pairs can define a function that decides if the elements in a list are sorted
- Using zip can define a function that returns the list of all positions of a value in a list
String Comprehensions-
- A string is a sequence of characters enclosed in double quotes. Internally, strings are represented as a lists of characters.
- Any polymorphic function that operates on lists can also be applied to strings
- List comprehensions can also work them